import React from "react";
import { Input } from "../ui/input";
import { Button } from "@/components/ui/button";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { ChromePicker } from "react-color";
import { cn } from "@/lib/utils";

function PopoverDemo({ value, onChange }) {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          className="rounded-l-none cursor-pointer px-[9px]"
        >
          <div
            className={cn("w-4 h-4", !value && "border border-dashed")}
            style={{
              backgroundColor: value,
            }}
          ></div>
        </Button>
      </PopoverTrigger>
      <PopoverContent className="p-0 w-auto shadow-none">
        <ChromePicker
          color={value}
          onChange={(color) => {
            onChange(color.hex);
          }}
          onChangeComplete={(e) => {
            onChange(e.hex);
          }}
        />
      </PopoverContent>
    </Popover>
  );
}

const ColorPicker = ({ value, onChange }) => {
  const handleColorChange = (event) => {
    onChange(event.target.value);
  };

  return (
    <div className="flex">
      <Input
        value={value}
        onChange={handleColorChange}
        className="flex-1 border-r-0 rounded-r-none"
      />
      <PopoverDemo value={value} onChange={onChange} />
    </div>
  );
};

export default ColorPicker;
